<template>
	<div class="color-predefine">
		<div class="color-predefine__colors">
			<div
				v-for="(item, index) in rgbaColors"
				:key="item.index"
				:class="{ selected: item.selected, 'is-alpha': item._alpha < 100 }"
				class="color-predefine__color-selector"
				@click="handleSelect(index)"
			>
				<div :style="{ backgroundColor: item.value }"></div>
			</div>
		</div>
	</div>
</template>

<script setup lang="ts">
import Color from '../util/color';
import { useOptions } from '../color-picker';
import { PreDefineProps } from '../color-picker';
const props = defineProps(PreDefineProps);
const currentColor: any = useOptions()?.currentColor; //当前颜色
/**
 * parseColors颜色事件
 * @param colors
 * @param color
 */
const parseColors = (colors: any, color: any) => {
	return colors.map((value: any) => {
		const c = new Color();
		c.enableAlpha = true;
		c.format = 'rgba';
		c.fromString(value);
		c.selected = c.value === color.value;
		return c;
	});
};
const rgbaColors = ref(parseColors(props.colors, props.color)); //管理rbga颜色

/**
 * 监听当前颜色
 */
watch(
	() => currentColor.value,
	(val: any) => {
		const color = new Color();
		color.fromString(val);
		rgbaColors.value.forEach((item: any) => {
			item.selected = color.compare(item);
		});
	}
);

watchEffect(() => {
	rgbaColors.value = parseColors(props.colors, props.color);
});

/**
 * handleSelect选择事件
 */
const handleSelect = (index: any) => {
	props.color.fromString(props.colors[index]);
};
</script>
